import Vue from 'vue'
import Router from 'vue-router'
import App from '../App'

// common
import Auth from '../common/Auth'

// components
Vue.use(Router)

let authBaseUrl = '/user'

// 懒加载组件，将组件chunk打包  尽量以懒加载的方式加载文件
const Login = resolve => require.ensure([], () => resolve(require('@/page/login')), 'login')
const Home = resolve => require.ensure([], () => resolve(require('@/page/homePage/home')), 'home')
const UserCenter = resolve => require.ensure([], () => resolve(require('@/page/userPage/userCenter')),'userCenter')
const ErrorPage = resolve => require.ensure([], () => resolve(require('@/page/errorPage/error')), 'error')

const router = new Router({
  routes: [
    {path: '/login', name: 'login', component: Login},
    {
      path: '/', // 顶级目录
      component: App,
      children: [ // 二级路由，对应app.vue
        {
          path: '',
          redirect: '/home'
        },
        {
          path: '/home',
          component: Home
        },
        {
          path: '/userCenter',
          component: UserCenter
        }
      ]
    },
    {path: '*', name: 'error', component: ErrorPage}
  ],
  beforeEach (to, from, next) {
    if (to.fullPath.startsWith('login') || to.fullPath === '/') {
      next()
      return
    }
    if (to.fullPath.startsWith(authBaseUrl)) {
      if (Auth.methods.authUser()) {
        console.log(Auth.methods.authUser())
      } else {
        next('/login')
        return
      }
    }
    next()
  }
})

export default router
